<template>
    <el-dialog :visible.sync="is_create_group_form_show" title="创建平台" :before-close="handleClose">
        <el-form ref="form" class="dialog-form" :model="form" label-position="right" :rules="rules" label-width="120px">
            <el-form-item label="名称：" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="我方开放部门：">
                <el-tree ref="create_group_tree" :data="sys_department_tree" check-strictly show-checkbox node-key="id" :props="props"></el-tree>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="onSubmit('form')">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import group from '@/api/group.js'
import { mapGetters } from 'vuex'

export default {
    name: 'group-create',
    props: ['is_create_group_form_show'],
    computed: {
        ...mapGetters('department1', ['sys_department_tree'])
    },
    data() {
        return {
            form: {
                name: undefined
            },
            rules: {
                name: [{
                    required: true, message: '请填写名称', trigger: 'blur'
                }]
            },
            props: {
                children: 'children',
                value: 'id',
                label: 'text'
            }
        }
    },
    methods: {
        handleClose() {
            this.$refs['form'].resetFields();
            this.$refs['create_group_tree'].setCheckedKeys([]);
            this.$emit('update:is_create_group_form_show', false)
        },
        onSubmit(formName) {
            let arr = this.$refs['create_group_tree'].getCheckedKeys()
            if(arr.length === 0) {
                this.$message.error('请选择部门!');
                return;
            }
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let params = {
                        groupName: this.form.name,
                        department: arr
                    }
                    await group.createGroup(params).then(res => {
                        this.$message({
                            type: 'success',
                            message: '创建成功!'
                        });
                        this.$store.dispatch('group/getGroupList');
                    }).catch(err => {
                        this.$message.error(err);
                    });
                    arr = null;
                    params = null;
                    this.handleClose();
                } else {
                    return false;
                }
            })
        }
    },
    mounted() {
        if(this.sys_department_tree === undefined) {
            this.$store.dispatch('department1/getSysDepartmentTree');
        }
    }
}
</script>

<style>

</style>
